import axios from 'axios';
import * as vscode from 'vscode';
import { handleContextAnalysisResult } from './codeFixSuggestionSystem'; // 导入修复建议系统
import { handleLSPAnalysisResult } from './codeFixSuggestionSystem2'; // 导入修复建议系统

// 配置
const LLM_SERVICE_URL = 'http://localhost:8000';
const REQUEST_TIMEOUT = 30000;

// 全局LLM分析开关状态
let llmAnalysisEnabled = true;

// 进度提示配置
const PROGRESS_CONFIG = {
  showDelay: 2000,      // 2秒后显示进度提示
  updateInterval: 1000, // 每秒更新一次进度
  maxWaitTime: 30000    // 最大等待时间30秒
};

// LSP分析队列配置
const LSP_QUEUE_CONFIG = {
  interval: 3000,        // 每3秒最多处理一个LSP请求
  maxQueueSize: 10,      // 最大队列长度
  maxRetries: 2          // 最大重试次数
};

// 上下文分析防抖配置  
const CONTEXT_DEBOUNCE_CONFIG = {
  debounceTime: 1500,    // 防抖时间1.5秒
  ignoreMultiple: true   // 忽略防抖期间的多个请求
};

// 代码块接口定义
interface CodeBlock {
  type: string;
  description: string;
  name?: string;
  entryCondition?: string;
  parameters?: string;
  range: {
    start: { line: number };
    end: { line: number };
  };
  depth: number;
  content: string;
}

// 上下文接口定义
interface CodeContext {
  currentBlock: CodeBlock | null;
  parentBlocks: CodeBlock[];
  childBlocks: CodeBlock[];
  siblings: CodeBlock[];
}

// LLM分析结果接口
interface LLMAnalysisResult {
  analysis: string;
  replaced_snippet: string;
  suggestions: string;
}

// LLM响应类型
interface LLMResponse {
  success: boolean;
  result?: LLMAnalysisResult;
  error?: string;
}

// LSP队列任务接口
interface LSPQueueTask {
  id: string;
  diagnostic: vscode.Diagnostic;
  doc: vscode.TextDocument;
  errorNode: any;
  semanticNode: any;
  classification: any;
  lspSuggestions?: any;
  timestamp: number;
  retryCount: number;
  resolve: (value: void) => void;
  reject: (reason?: any) => void;
}

// 上下文分析任务接口
interface ContextTask {
  id: string;
  context: CodeContext;
  doc: vscode.TextDocument;
  position: vscode.Position;
  timestamp: number;
}

// 进度追踪器接口
interface ProgressTracker {
  taskId: string;
  type: 'lsp' | 'context';
  startTime: number;
  progress: vscode.Progress<{message?: string; increment?: number}>;
  token: vscode.CancellationToken;
  resolve: () => void;
}

/**
 * 进度管理器
 */
class ProgressManager {
  private activeTrackers = new Map<string, ProgressTracker>();
  private progressTimers = new Map<string, NodeJS.Timeout>();

  /**
   * 开始追踪任务进度
   */
  async startProgress(taskId: string, type: 'lsp' | 'context', title: string): Promise<void> {
    // 延迟显示进度提示
    const timer = setTimeout(() => {
      this.showProgressNotification(taskId, type, title);
    }, PROGRESS_CONFIG.showDelay);

    this.progressTimers.set(taskId, timer);
  }

  /**
   * 显示进度通知
   */
  private async showProgressNotification(taskId: string, type: 'lsp' | 'context', title: string): Promise<void> {
    const typeText = type === 'lsp' ? 'LSP错误' : '代码上下文';
    
    await vscode.window.withProgress(
      {
        location: vscode.ProgressLocation.Notification,
        title: `正在分析${typeText}...`,
        cancellable: true
      },
      async (progress, token) => {
        return new Promise<void>((resolve) => {
          const tracker: ProgressTracker = {
            taskId,
            type,
            startTime: Date.now(),
            progress,
            token,
            resolve
          };

          this.activeTrackers.set(taskId, tracker);

          // 开始更新进度
          this.updateProgress(taskId);

          // 处理取消操作
          token.onCancellationRequested(() => {
            this.stopProgress(taskId);
            vscode.window.showWarningMessage(`${typeText}分析已取消`);
          });
        });
      }
    );
  }

  /**
   * 更新进度显示
   */
  private updateProgress(taskId: string): void {
    const tracker = this.activeTrackers.get(taskId);
    if (!tracker) return;

    const elapsed = Date.now() - tracker.startTime;
    const seconds = Math.floor(elapsed / 1000);
    
    let message: string;
    if (seconds < 5) {
      message = "正在连接LLM服务...";
    } else if (seconds < 10) {
      message = "正在分析代码结构...";
    } else if (seconds < 20) {
      message = "正在生成智能建议...";
    } else {
      message = `分析中，已用时 ${seconds} 秒...`;
    }

    tracker.progress.report({ message });

    // 检查是否超时
    if (elapsed >= PROGRESS_CONFIG.maxWaitTime) {
      this.stopProgress(taskId);
      vscode.window.showErrorMessage('LLM分析超时，请检查服务状态');
      return;
    }

    // 如果任务还在进行，继续更新
    if (this.activeTrackers.has(taskId)) {
      setTimeout(() => this.updateProgress(taskId), PROGRESS_CONFIG.updateInterval);
    }
  }

  /**
   * 停止进度追踪
   */
  stopProgress(taskId: string): void {
    // 清除延迟定时器
    const timer = this.progressTimers.get(taskId);
    if (timer) {
      clearTimeout(timer);
      this.progressTimers.delete(taskId);
    }

    // 结束进度显示
    const tracker = this.activeTrackers.get(taskId);
    if (tracker) {
      tracker.resolve();
      this.activeTrackers.delete(taskId);
    }
  }

  /**
   * 清理所有进度
   */
  clear(): void {
    // 清除所有定时器
    for (const timer of this.progressTimers.values()) {
      clearTimeout(timer);
    }
    this.progressTimers.clear();

    // 结束所有进度显示
    for (const tracker of this.activeTrackers.values()) {
      tracker.resolve();
    }
    this.activeTrackers.clear();
  }

  /**
   * 获取当前活跃的分析任务
   */
  getActiveAnalysis(): Array<{taskId: string; type: string; duration: number}> {
    const result = [];
    for (const [taskId, tracker] of this.activeTrackers) {
      result.push({
        taskId,
        type: tracker.type === 'lsp' ? 'LSP错误分析' : '代码上下文分析',
        duration: Date.now() - tracker.startTime
      });
    }
    return result;
  }
}

/**
 * LSP错误分析队列管理器
 */
class LSPAnalysisQueue {
  private queue: LSPQueueTask[] = [];
  private processing = false;
  private lastProcessTime = 0;
  private processingTimer?: NodeJS.Timeout;

  /**
   * 添加LSP分析任务到队列
   */
  async enqueue(
    diagnostic: vscode.Diagnostic,
    doc: vscode.TextDocument,
    errorNode: any,
    semanticNode: any,
    classification: any,
    lspSuggestions?: any
  ): Promise<void> {
    // 检查LLM分析是否启用
    if (!llmAnalysisEnabled) {
      console.log('LLM分析已禁用，跳过LSP错误分析');
      return;
    }

    return new Promise((resolve, reject) => {
      const taskId = this.generateTaskId(diagnostic, doc);
      
      // 检查是否已存在相同的任务（去重）
      const existingIndex = this.queue.findIndex(task => task.id === taskId);
      if (existingIndex !== -1) {
        console.log(`LSP分析任务已存在，更新任务: ${taskId}`);
        // 更新现有任务，保持在原位置
        this.queue[existingIndex] = {
          ...this.queue[existingIndex],
          diagnostic,
          errorNode,
          semanticNode,
          classification,
          lspSuggestions,
          timestamp: Date.now(),
          resolve,
          reject
        };
        return;
      }

      // 检查队列长度限制
      if (this.queue.length >= LSP_QUEUE_CONFIG.maxQueueSize) {
        console.log(`LSP分析队列已满，丢弃最旧的任务`);
        const oldTask = this.queue.shift();
        if (oldTask) {
          oldTask.reject(new Error('队列已满，任务被丢弃'));
        }
      }

      // 添加新任务
      const task: LSPQueueTask = {
        id: taskId,
        diagnostic,
        doc,
        errorNode,
        semanticNode,
        classification,
        lspSuggestions,
        timestamp: Date.now(),
        retryCount: 0,
        resolve,
        reject
      };

      this.queue.push(task);
      console.log(`LSP分析任务入队: ${taskId} (队列长度: ${this.queue.length})`);
      
      // 启动处理
      this.startProcessing();
    });
  }

  /**
   * 开始处理队列
   */
  private startProcessing(): void {
    if (this.processing || this.queue.length === 0) {
      return;
    }

    const now = Date.now();
    const timeSinceLastProcess = now - this.lastProcessTime;
    
    if (timeSinceLastProcess >= LSP_QUEUE_CONFIG.interval) {
      // 可以立即处理
      this.processNext();
    } else {
      // 需要等待
      const waitTime = LSP_QUEUE_CONFIG.interval - timeSinceLastProcess;
      console.log(`LSP队列等待 ${waitTime}ms 后处理下一个任务`);
      
      this.processingTimer = setTimeout(() => {
        this.processNext();
      }, waitTime);
    }
  }

  /**
   * 处理队列中的下一个任务
   */
  private async processNext(): Promise<void> {
    if (this.queue.length === 0) {
      this.processing = false;
      return;
    }

    this.processing = true;
    this.lastProcessTime = Date.now();

    const task = this.queue.shift()!;
    console.log(`开始处理LSP分析任务: ${task.id}`);

    // 开始进度追踪
    progressManager.startProgress(task.id, 'lsp', 'LSP错误分析');

    try {
      const errorText = this.generateLSPErrorText(
        task.diagnostic,
        task.doc,
        task.errorNode,
        task.semanticNode,
        task.classification,
        task.lspSuggestions
      );

      const response = await this.sendToLLMCore(errorText, 'lsp_error', task.doc);
      
      if (response && response.result) {
        this.displayLSPErrorResult(response.result);
        task.resolve();
        await handleLSPAnalysisResult(response.result, task.diagnostic, task.doc);
      } else {
        throw new Error('LLM返回结果为空');
      }

    } catch (error) {
      console.log(`LSP分析任务失败: ${task.id}, 错误: ${error}`);
      
      // 重试逻辑
      if (task.retryCount < LSP_QUEUE_CONFIG.maxRetries) {
        task.retryCount++;
        task.timestamp = Date.now();
        this.queue.unshift(task); // 重新放回队列头部
        console.log(`LSP任务重试 ${task.retryCount}/${LSP_QUEUE_CONFIG.maxRetries}: ${task.id}`);
      } else {
        console.log(`LSP任务最终失败: ${task.id}`);
        task.reject(error);
      }
    }

    this.processing = false;
    
    // 继续处理下一个任务
    setTimeout(() => {
      this.startProcessing();
    }, 100); // 短暂延迟后处理下一个
  }

  /**
   * 生成任务ID（用于去重）
   */
  private generateTaskId(diagnostic: vscode.Diagnostic, doc: vscode.TextDocument): string {
    const line = diagnostic.range.start.line;
    const character = diagnostic.range.start.character;
    const message = diagnostic.message.substring(0, 50); // 取错误消息前50字符
    return `${doc.uri.toString()}-${line}-${character}-${message}`;
  }

  /**
   * 获取队列状态
   */
  getStatus(): {
    queueLength: number;
    processing: boolean;
    lastProcessTime: number;
    nextProcessTime: number;
  } {
    const now = Date.now();
    const timeSinceLastProcess = now - this.lastProcessTime;
    const nextProcessTime = this.processing ? 
      0 : 
      Math.max(0, LSP_QUEUE_CONFIG.interval - timeSinceLastProcess);

    return {
      queueLength: this.queue.length,
      processing: this.processing,
      lastProcessTime: this.lastProcessTime,
      nextProcessTime
    };
  }

  /**
   * 清空队列
   */
  clear(): void {
    // 取消所有待处理任务
    this.queue.forEach(task => {
      task.reject(new Error('队列被清空'));
    });
    this.queue = [];
    
    // 清除定时器
    if (this.processingTimer) {
      clearTimeout(this.processingTimer);
      this.processingTimer = undefined;
    }
    
    this.processing = false;
    console.log('LSP分析队列已清空');
  }

  /**
   * 生成LSP错误文本
   */
  private generateLSPErrorText(
    diagnostic: vscode.Diagnostic,
    doc: vscode.TextDocument,
    errorNode: any,
    semanticNode: any,
    classification: any,
    lspSuggestions?: any
  ): string {
    const errorLine = diagnostic.range.start.line;
    const errorColumn = diagnostic.range.start.character;
    
    let text = `=== LSP错误分析 ===\n`;
    text += `文件: ${doc.fileName}\n`;
    text += `语言: ${doc.languageId}\n`;
    text += `错误位置: 行${errorLine + 1}, 列${errorColumn + 1}\n\n`;
    
    text += `错误信息:\n`;
    text += `- 类型: ${classification.category}\n`;
    text += `- 消息: ${diagnostic.message}\n`;
    text += `- 优先级: ${classification.priority}\n\n`;
    
    text += `AST节点信息:\n`;
    text += `- 错误节点类型: ${errorNode.type}\n`;
    text += `- 错误节点内容: ${this.truncateText(errorNode.text, 100)}\n`;
    text += `- 语义节点类型: ${semanticNode.type}\n`;
    
    if (semanticNode.parent) {
      text += `- 父节点类型: ${semanticNode.parent.type}\n`;
    }
    
    // 添加代码上下文
    text += `\n代码上下文:\n`;
    const startLine = Math.max(0, errorLine - 2);
    const endLine = Math.min(doc.lineCount - 1, errorLine + 2);
    
    for (let i = startLine; i <= endLine; i++) {
      const lineText = doc.lineAt(i).text;
      const marker = i === errorLine ? ' > ' : '   ';
      text += `${(i + 1).toString().padStart(3)}${marker}${lineText}\n`;
    }
    
    // 添加LSP建议（如果有）
    if (lspSuggestions) {
      text += `\nLSP建议:\n`;
      
      if (lspSuggestions.functionInfo) {
        text += `- 函数信息: ${lspSuggestions.functionInfo}\n`;
      }
      
      if (lspSuggestions.hoverInfo) {
        text += `- 类型信息: ${lspSuggestions.hoverInfo}\n`;
      }
      
      if (lspSuggestions.signatures && lspSuggestions.signatures.length > 0) {
        text += `- 函数签名: ${lspSuggestions.signatures.join(', ')}\n`;
      }
      
      if (lspSuggestions.completions && lspSuggestions.completions.length > 0) {
        text += `- 可能选项: ${lspSuggestions.completions.slice(0, 5).join(', ')}\n`;
      }
    }
    
    return text;
  }

  /**
   * 发送到LLM核心函数
   */
  private async sendToLLMCore(
    content: string,
    type: string,
    doc: vscode.TextDocument
  ): Promise<LLMResponse | null> {
    try {
      console.log(`正在发送LSP错误到LLM分析...`);
      
      const response = await axios.post(
        `${LLM_SERVICE_URL}/api/analyze`,
        {
          prompt: content,
          type,
          filePath: doc.uri.fsPath,
          languageId: doc.languageId,
          timestamp: Date.now()
        },
        {
          timeout: REQUEST_TIMEOUT,
          headers: {
            'Content-Type': 'application/json'
          }
        }
      );
      
      if (response.data.success) {
        console.log(`LSP错误分析完成`);
        return response.data;
      } else {
        console.log(`LSP错误分析失败: ${response.data.error}`);
        return null;
      }
    } catch (error) {
      if (axios.isAxiosError(error)) {
        if (error.code === 'ECONNREFUSED') {
          console.log(`提示: LLM分析服务未启动 (${LLM_SERVICE_URL})`);
        } else if (error.code === 'ENOTFOUND') {
          console.log(`提示: 无法连接到LLM分析服务`);
        } else {
          console.log(`LLM分析请求失败: ${error.message}`);
        }
      }
      throw error;
    }
  }

  /**
   * 显示LSP错误分析结果
   */
  private displayLSPErrorResult(result: LLMAnalysisResult): void {
    console.log(`\n========== LSP错误智能分析 ==========`);
    
    console.log(`\n错误诊断:`);
    console.log(result.analysis);
    
    console.log(`\n修复建议:`);
    console.log(result.suggestions);
    
    console.log('==========================================\n');
  }

  /**
   * 工具函数：截断文本
   */
  private truncateText(text: string, maxLength: number): string {
    if (text.length <= maxLength) return text;
    return text.substring(0, maxLength - 3) + '...';
  }
}

/**
 * 上下文分析防抖管理器
 */
class ContextAnalysisDebouncer {
  private debounceTimer?: NodeJS.Timeout;
  private lastRequestTime = 0;
  private pendingTask?: ContextTask;

  /**
   * 防抖处理上下文分析请求
   */
  async debounce(
    context: CodeContext,
    doc: vscode.TextDocument,
    position: vscode.Position
  ): Promise<void> {
    // 检查LLM分析是否启用
    if (!llmAnalysisEnabled) {
      console.log('LLM分析已禁用，跳过代码上下文分析');
      return;
    }

    const now = Date.now();
    const taskId = this.generateTaskId(doc, position);

    // 如果配置为忽略多个请求，且在防抖期间，则直接返回
    if (CONTEXT_DEBOUNCE_CONFIG.ignoreMultiple) {
      const timeSinceLastRequest = now - this.lastRequestTime;
      if (timeSinceLastRequest < CONTEXT_DEBOUNCE_CONFIG.debounceTime) {
        console.log(`上下文分析请求过于频繁，忽略请求: ${taskId} (距上次 ${timeSinceLastRequest}ms)`);
        return;
      }
    }

    // 取消之前的定时器
    if (this.debounceTimer) {
      clearTimeout(this.debounceTimer);
    }

    // 创建新的待处理任务
    this.pendingTask = {
      id: taskId,
      context,
      doc,
      position,
      timestamp: now
    };

    console.log(`上下文分析请求已接收，将在 ${CONTEXT_DEBOUNCE_CONFIG.debounceTime}ms 后处理: ${taskId}`);

    // 设置新的防抖定时器
    this.debounceTimer = setTimeout(async () => {
      if (this.pendingTask) {
        await this.processContextAnalysis(this.pendingTask);
        this.pendingTask = undefined;
      }
    }, CONTEXT_DEBOUNCE_CONFIG.debounceTime);
  }

  /**
   * 立即执行上下文分析（跳过防抖）
   */
  async immediate(
    context: CodeContext,
    doc: vscode.TextDocument,
    position: vscode.Position
  ): Promise<void> {
    // 检查LLM分析是否启用
    if (!llmAnalysisEnabled) {
      console.log('LLM分析已禁用，跳过代码上下文分析');
      return;
    }

    // 取消防抖定时器
    if (this.debounceTimer) {
      clearTimeout(this.debounceTimer);
      this.debounceTimer = undefined;
    }

    const task: ContextTask = {
      id: this.generateTaskId(doc, position),
      context,
      doc,
      position,
      timestamp: Date.now()
    };

    console.log(`立即执行上下文分析: ${task.id}`);
    await this.processContextAnalysis(task);
  }

  /**
   * 处理上下文分析
   */
  private async processContextAnalysis(task: ContextTask): Promise<void> {
    // 开始进度追踪
    progressManager.startProgress(task.id, 'context', '代码上下文分析');

    try {
      this.lastRequestTime = task.timestamp;
      console.log(`开始处理上下文分析: ${task.id}`);

      const contextText = this.generateContextText(task.context, task.doc, task.position);
      const response = await this.sendToLLMCore(contextText, 'code_context', task.doc);
      
      if (response && response.result) {
        this.displayContextAnalysisResult(response.result);
        const virtualDiagnostic = new vscode.Diagnostic(
            new vscode.Range(task.position, task.position),
            "代码上下文优化建议",
            vscode.DiagnosticSeverity.Information
          );
        await handleContextAnalysisResult(response.result, virtualDiagnostic, task.doc);
      }
      
      console.log(`上下文分析完成: ${task.id}`);
    } catch (error) {
      console.log(`上下文分析失败: ${task.id}, 错误: ${error}`);
    } finally {
      // 停止进度追踪
      progressManager.stopProgress(task.id);
    }
  }

  /**
   * 生成任务ID
   */
  private generateTaskId(doc: vscode.TextDocument, position: vscode.Position): string {
    return `${doc.uri.toString()}-${position.line}-${position.character}`;
  }

  /**
   * 生成上下文文本
   */
  private generateContextText(
    context: CodeContext,
    doc: vscode.TextDocument,
    position: vscode.Position
  ): string {
    let text = `=== 代码上下文分析 ===\n`;
    text += `文件: ${doc.fileName}\n`;
    text += `语言: ${doc.languageId}\n`;
    text += `光标位置: 行${position.line + 1}, 列${position.character + 1}\n\n`;
    
    if (!context.currentBlock) {
      text += `当前位置: 未识别到特定代码块\n`;
      return text;
    }
    
    text += `当前代码块:\n`;
    text += `- 类型: ${context.currentBlock.type}\n`;
    text += `- 描述: ${context.currentBlock.description}\n`;
    
    if (context.currentBlock.name) {
      text += `- 名称: ${context.currentBlock.name}\n`;
    }
    
    if (context.currentBlock.entryCondition) {
      text += `- 入口条件: ${context.currentBlock.entryCondition}\n`;
    }
    
    if (context.currentBlock.parameters !== undefined) {
      text += `- 参数: ${context.currentBlock.parameters || '()'}\n`;
    }
    
    text += `- 位置: 行${context.currentBlock.range.start.line + 1}-${context.currentBlock.range.end.line + 1}\n`;
    text += `- 嵌套深度: ${context.currentBlock.depth}\n`;
    
    text += `- 代码内容:\n\t${context.currentBlock.content}\n\n`;
    
    // 父级代码块
    if (context.parentBlocks.length > 0) {
      text += `父级代码块:\n`;
      context.parentBlocks.forEach((block: CodeBlock, index: number) => {
        const indent = '  '.repeat(index);
        text += `${indent}- ${block.description}`;
        if (block.entryCondition) {
          text += ` (条件: ${block.entryCondition})`;
        }
        if (block.parameters !== undefined) {
          text += ` (参数: ${block.parameters || '()'})`;
        }
        text += `\n`;
      });
      text += `\n`;
    }
    
    // 子代码块
    if (context.childBlocks.length > 0) {
      text += `子代码块:\n`;
      context.childBlocks.forEach((block: CodeBlock, index: number) => {
        text += `  ${index + 1}. ${block.description}`;
        if (block.entryCondition) {
          text += ` (条件: ${block.entryCondition})`;
        }
        text += `\n`;
      });
      text += `\n`;
    }
    
    // 同级代码块
    if (context.siblings.length > 0) {
      text += `同级代码块:\n`;
      context.siblings.forEach((block: CodeBlock, index: number) => {
        text += `  ${index + 1}. ${block.description}`;
        if (block.entryCondition) {
          text += ` (条件: ${block.entryCondition})`;
        }
        text += `\n`;
      });
    }
    
    return text;
  }

  /**
   * 发送到LLM核心函数
   */
  private async sendToLLMCore(
    content: string,
    type: string,
    doc: vscode.TextDocument
  ): Promise<LLMResponse | null> {
    try {
      console.log(`正在发送代码上下文到LLM分析...`);
      
      const response = await axios.post(
        `${LLM_SERVICE_URL}/api/analyze`,
        {
          prompt: content,
          type,
          filePath: doc.uri.fsPath,
          languageId: doc.languageId,
          timestamp: Date.now()
        },
        {
          timeout: REQUEST_TIMEOUT,
          headers: {
            'Content-Type': 'application/json'
          }
        }
      );
      
      if (response.data.success) {
        console.log(`代码上下文分析完成`);
        return response.data;
      } else {
        console.log(`代码上下文分析失败: ${response.data.error}`);
        return null;
      }
    } catch (error) {
      if (axios.isAxiosError(error)) {
        if (error.code === 'ECONNREFUSED') {
          console.log(`提示: LLM分析服务未启动 (${LLM_SERVICE_URL})`);
        } else if (error.code === 'ENOTFOUND') {
          console.log(`提示: 无法连接到LLM分析服务`);
        } else {
          console.log(`LLM分析请求失败: ${error.message}`);
        }
      }
      throw error;
    }
  }

  /**
   * 显示代码上下文分析结果
   */
  private displayContextAnalysisResult(result: LLMAnalysisResult): void {
    console.log(`\n========== 代码上下文智能分析 ==========`);
    
    console.log(`\n上下文理解:`);
    console.log(result.analysis);
    
    console.log(`\n优化建议:`);
    console.log(result.suggestions);
    
    console.log('=============================================\n');
  }

  /**
   * 获取防抖状态
   */
  getStatus(): {
    isPending: boolean;
    lastRequestTime: number;
    pendingTaskId?: string;
    remainingDebounceTime: number;
  } {
    const now = Date.now();
    const remainingTime = this.debounceTimer ? 
      Math.max(0, CONTEXT_DEBOUNCE_CONFIG.debounceTime - (now - (this.pendingTask?.timestamp || 0))) : 
      0;

    return {
      isPending: !!this.debounceTimer,
      lastRequestTime: this.lastRequestTime,
      pendingTaskId: this.pendingTask?.id,
      remainingDebounceTime: remainingTime
    };
  }

  /**
   * 清空防抖器
   */
  clear(): void {
    if (this.debounceTimer) {
      clearTimeout(this.debounceTimer);
      this.debounceTimer = undefined;
    }
    this.pendingTask = undefined;
    console.log('上下文分析防抖器已清空');
  }
}

// 全局实例
const lspQueue = new LSPAnalysisQueue();
const contextDebouncer = new ContextAnalysisDebouncer();
const progressManager = new ProgressManager();

// ============ 导出的LLM分析开关功能 ============

/**
 * 切换LLM分析开关状态
 */
export function toggleLLMAnalysis(): void {
  llmAnalysisEnabled = !llmAnalysisEnabled;
  
  const status = llmAnalysisEnabled ? '已启用' : '已禁用';
  const statusIcon = llmAnalysisEnabled ? '🟢' : '🔴';
  
  console.log(`LLM智能分析 ${status}`);
  vscode.window.showInformationMessage(`${statusIcon} LLM智能分析 ${status}`);
  
  // 如果禁用了LLM分析，清理所有待处理的任务
  if (!llmAnalysisEnabled) {
    lspQueue.clear();
    contextDebouncer.clear();
    progressManager.clear();
    vscode.window.showInformationMessage('已清理所有待处理的分析任务');
  }
  
  // 更新状态栏
  updateStatusBarItem();
}

/**
 * 获取LLM分析开关状态
 */
export function isLLMAnalysisEnabled(): boolean {
  return llmAnalysisEnabled;
}

/**
 * 设置LLM分析开关状态
 */
export function setLLMAnalysisEnabled(enabled: boolean): void {
  const wasEnabled = llmAnalysisEnabled;
  llmAnalysisEnabled = enabled;
  
  if (wasEnabled !== enabled) {
    const status = enabled ? '已启用' : '已禁用';
    const statusIcon = enabled ? '🟢' : '🔴';
    
    console.log(`LLM智能分析 ${status}`);
    vscode.window.showInformationMessage(`${statusIcon} LLM智能分析 ${status}`);
    
    // 如果禁用了LLM分析，清理所有待处理的任务
    if (!enabled) {
      lspQueue.clear();
      contextDebouncer.clear();
      progressManager.clear();
    }
    
    // 更新状态栏
    updateStatusBarItem();
  }
}

// 状态栏项目
let statusBarItem: vscode.StatusBarItem;

/**
 * 初始化状态栏
 */
export function initializeStatusBar(): void {
  statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 100);
  statusBarItem.command = 'extension.toggleLLMAnalysis';
  statusBarItem.tooltip = '点击切换LLM智能分析开关状态';
  updateStatusBarItem();
  statusBarItem.show();
}

/**
 * 更新状态栏显示
 */
function updateStatusBarItem(): void {
  if (statusBarItem) {
    const statusIcon = llmAnalysisEnabled ? '🟢' : '🔴';
    const statusText = llmAnalysisEnabled ? 'LLM分析:ON' : 'LLM分析:OFF';
    statusBarItem.text = `${statusIcon} ${statusText}`;
  }
}

/**
 * 注册VS Code命令和快捷键
 * 这个函数应该在扩展的activate函数中调用
 */
export function registerCommands(context: vscode.ExtensionContext): void {
  // 注册切换命令
  const toggleCommand = vscode.commands.registerCommand('extension.toggleLLMAnalysis', () => {
    toggleLLMAnalysis();
  });
  
  // 注册查看状态命令
  const statusCommand = vscode.commands.registerCommand('extension.showLLMAnalysisStatus', () => {
    showDetailedStatus();
  });
  
  // 注册清理命令
  const cleanupCommand = vscode.commands.registerCommand('extension.cleanupLLMAnalysis', () => {
    cleanup();
    vscode.window.showInformationMessage('LLM分析任务已全部清理');
  });

  context.subscriptions.push(toggleCommand, statusCommand, cleanupCommand);
  
  // 初始化状态栏
  initializeStatusBar();
  context.subscriptions.push(statusBarItem);
}

/**
 * 显示详细状态信息
 */
function showDetailedStatus(): void {
  const overallStatus = getOverallStatus();
  const activeAnalysis = progressManager.getActiveAnalysis();
  
  let message = `LLM智能分析状态: ${llmAnalysisEnabled ? '已启用 🟢' : '已禁用 🔴'}\n\n`;
  
  message += `LSP错误分析队列:\n`;
  message += `- 队列长度: ${overallStatus.lspQueue.queueLength}\n`;
  message += `- 正在处理: ${overallStatus.lspQueue.processing ? '是' : '否'}\n\n`;
  
  message += `代码上下文分析:\n`;
  message += `- 待处理: ${overallStatus.contextDebounce.isPending ? '是' : '否'}\n`;
  message += `- 剩余防抖时间: ${overallStatus.contextDebounce.remainingDebounceTime}ms\n\n`;
  
  if (activeAnalysis.length > 0) {
    message += `当前正在进行的分析:\n`;
    activeAnalysis.forEach((analysis, index) => {
      message += `${index + 1}. ${analysis.type} (已用时: ${Math.floor(analysis.duration / 1000)}秒)\n`;
    });
  } else {
    message += `当前没有正在进行的分析任务\n`;
  }
  
  vscode.window.showInformationMessage(message, { modal: true });
}

// ============ 原有的导出函数 ============

/**
 * 发送LSP错误信息给LLM分析（队列方式）
 */
export async function sendLSPErrorToLLM(
  diagnostic: vscode.Diagnostic,
  doc: vscode.TextDocument,
  errorNode: any,
  semanticNode: any,
  classification: any,
  lspSuggestions?: any
): Promise<void> {
  try {
    await lspQueue.enqueue(diagnostic, doc, errorNode, semanticNode, classification, lspSuggestions);
  } catch (error) {
    console.log(`LSP错误分析入队失败: ${error}`);
  }
}

/**
 * 发送代码上下文信息给LLM分析（防抖方式）
 */
export async function sendContextToLLM(
  context: CodeContext,
  doc: vscode.TextDocument,
  position: vscode.Position
): Promise<void> {
  try {
    await contextDebouncer.debounce(context, doc, position);
  } catch (error) {
    console.log(`代码上下文分析失败: ${error}`);
  }
}

/**
 * 立即发送上下文分析（跳过防抖）
 */
export async function sendContextToLLMImmediate(
  context: CodeContext,
  doc: vscode.TextDocument,
  position: vscode.Position
): Promise<void> {
  try {
    await contextDebouncer.immediate(context, doc, position);
  } catch (error) {
    console.log(`立即上下文分析失败: ${error}`);
  }
}

/**
 * 配置LLM服务地址
 */
export function configureLLMService(baseURL: string): void {
  console.log(`LLM服务地址配置为: ${baseURL}`);
}

/**
 * 获取LSP队列状态
 */
export function getLSPQueueStatus() {
  return lspQueue.getStatus();
}

/**
 * 获取上下文防抖状态
 */
export function getContextDebounceStatus() {
  return contextDebouncer.getStatus();
}

/**
 * 获取整体状态
 */
export function getOverallStatus(): {
  lspQueue: ReturnType<typeof getLSPQueueStatus>;
  contextDebounce: ReturnType<typeof getContextDebounceStatus>;
  config: {
    lspQueueConfig: typeof LSP_QUEUE_CONFIG;
    contextDebounceConfig: typeof CONTEXT_DEBOUNCE_CONFIG;
  };
  analysisEnabled: boolean;
  activeAnalysis: Array<{taskId: string; type: string; duration: number}>;
} {
  return {
    lspQueue: getLSPQueueStatus(),
    contextDebounce: getContextDebounceStatus(),
    config: {
      lspQueueConfig: LSP_QUEUE_CONFIG,
      contextDebounceConfig: CONTEXT_DEBOUNCE_CONFIG
    },
    analysisEnabled: llmAnalysisEnabled,
    activeAnalysis: progressManager.getActiveAnalysis()
  };
}

/**
 * 清理所有待处理的请求（在扩展停用时调用）
 */
export function cleanup(): void {
  lspQueue.clear();
  contextDebouncer.clear();
  progressManager.clear();
  console.log(`LLM分析服务已清理`);
}